import React, { useState, useEffect, useRef } from 'react';
import { View, Text } from '@tarojs/components';

import './tabs.scss';

const Tabs = ({ tabsList = [], getCurrentTab = null, defaultTab = 0 }) => {
  const [currentTab, setCurrentTab] = useState(defaultTab);
  const hasChanged = useRef(false);

  const setTab = (index) => {
    if (index !== currentTab) {
      if (!hasChanged.current) {
        hasChanged.current = true;
      }
      setCurrentTab(index);
    }
  };

  useEffect(() => {
    if (getCurrentTab && hasChanged.current) {
      getCurrentTab(currentTab);
    }
  }, [currentTab]);

  return (
    <View className="homePageTabs">
      {tabsList.map((tab, index) => (
        <View
          className={['item', currentTab === index && 'actItem'].join(' ')}
          onClick={() => setTab(index)}
          key={tab.label + '_' + index}
        >
          <Text className={['label', currentTab === index && 'actLabel'].join(' ')}>
            {tab.label}
          </Text>
          <Text className={['subLabel', currentTab === index && 'actSubLabel'].join(' ')}>
            {tab.subLabel}
          </Text>
        </View>
      ))}
    </View>
  );
};

export default Tabs;
